package com.itheima.thread.threadPool.countDownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Ethan Yankang
 * @Program: Interview
 * @Date: 2024-08-16 08:34
 **/
public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
//        定义任务数量
        int taskCount=5;
//        创建一个countDownCount，计数器初始化为任务数量
        CountDownLatch countDownLatch = new CountDownLatch(taskCount);
//        创建一个固定大小的线程池
        ExecutorService es = Executors.newFixedThreadPool(3);
        for (int i = 0; i < taskCount; i++) {
            final int taskId=i;
            es.submit(()->{
//                模拟任务执行时间
                try {
                    System.out.println("Task"+taskId+"is been processed by"+Thread.currentThread().getName());
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        System.err.println("这是在await()之前执行的，线程穿插执行");
        countDownLatch.await();
        System.err.println("这是在await()之后执行的，线程等待计数器结束后执行");
        System.out.println("All task are completed");
//        关闭线程池
        es.shutdown();
    }
}
